package com.junzhiit.nengji.shop.web.util.printing;

import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bainaeco.framework.util.HttpClientUtils;

public class PrintingUtil {

	private static Log logger = LogFactory.getLog(PrintingUtil.class);
	
	private static final String GET_ACCESS_TOKEN = "https://open-api.10ss.net/oauth/oauth";
	private static final String PUT_ACCESS_TOKEN = "https://open-api.10ss.net/oauth/oauth";
	private static final String PRINTER_ADD_PRINTER = "https://open-api.10ss.net/printer/addprinter";
	private static final String PRINT_INDEX = "https://open-api.10ss.net/print/index";
	
	//获取access_token
	public static JSONObject oauthOauth(String clientId,String clientSecret){
		JSONObject json = new JSONObject();
		Map<String,String> params = new HashMap<String,String>();
		String timestamp = getTimestamp();
		String UUID4 = UUID.randomUUID().toString();
		String sign = MD5_SHA(clientId+timestamp+clientSecret,"MD5").toLowerCase();
		
		params.put("client_id", clientId);
		params.put("grant_type", "client_credentials");
		params.put("sign", sign);
		params.put("scope", "all");
		params.put("timestamp", timestamp);
		params.put("id", UUID4);
		try {
			String result = HttpClientUtils.postMethodRequest(GET_ACCESS_TOKEN, params);
			json = (JSONObject) JSON.parse(result);
			logger.info(result);
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return json;
	}
	
	//更新access_token
	public static JSONObject oauthOauth(String clientId,String clientSecret,String refreshToken){
		JSONObject json = new JSONObject();
		Map<String,String> params = new HashMap<String,String>();
		String timestamp = getTimestamp();
		String UUID4 = getUUID();
		String sign = MD5_SHA(clientId+timestamp+clientSecret,"MD5").toLowerCase();
		
		params.put("client_id", clientId);
		params.put("grant_type", "refresh_token");
		params.put("scope", "all");
		params.put("sign", sign);
		params.put("refresh_token", UUID4);
		params.put("timestamp", timestamp);
		params.put("id", UUID4);
		
		try {
			String result = HttpClientUtils.postMethodRequest(PUT_ACCESS_TOKEN, params);
			json = (JSONObject) JSON.parse(result);
			logger.info(result);
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return json;
	}
	
	//永久授权
	public static JSONObject printerAddprinter(String clientId,String clientSecret,String machineCode,String msign,String accessToken){
		JSONObject json = new JSONObject();
		Map<String,String> params = new HashMap<String,String>();
		String timestamp = getTimestamp();
		String UUID4 = getUUID();
		String sign = MD5_SHA(clientId+timestamp+clientSecret,"MD5").toLowerCase();
		
		params.put("client_id", clientId);
		params.put("access_token", accessToken);
		params.put("sign", sign);
		params.put("msign", msign);
		params.put("machine_code", machineCode);
		params.put("timestamp", timestamp);
		params.put("id", UUID4);
		
		try {
			String result = HttpClientUtils.postMethodRequest(PRINTER_ADD_PRINTER, params);
			json = (JSONObject) JSON.parse(result);
			logger.info(result);
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return json;
	}
	
	//打印文本
	public static JSONObject printIndex(String clientId,String clientSecret,String machineCode,String originId,String accessToken,String content){
		JSONObject json = new JSONObject();
		Map<String,String> params = new HashMap<String,String>();
		String timestamp = getTimestamp();
		String UUID4 = getUUID();
		String sign = MD5_SHA(clientId+timestamp+clientSecret,"MD5").toLowerCase();
		
		params.put("client_id", clientId);
		params.put("access_token", accessToken);
		params.put("sign", sign);
		params.put("machine_code", machineCode);
		params.put("origin_id", originId);
		params.put("timestamp", timestamp);
		params.put("content", content);
		params.put("id", UUID4);
		
		try {
			String result = HttpClientUtils.postMethodRequest(PRINT_INDEX, params);
			json = (JSONObject) JSON.parse(result);
			logger.info(result);
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return json;
	}
	
	public static String getTimestamp(){
		return new Date().getTime()+"";
	}
	
	public static String getUUID(){
		return UUID.randomUUID().toString();
	}
	
	//MD5或者SHA加密
	private final static String MD5_SHA(String s, String method) {  
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
                'a', 'b', 'c', 'd', 'e', 'f' };  
        try {  
            byte[] strTemp = s.getBytes();  
            //如果输入“SHA”，就是实现SHA加密。  
            MessageDigest mdTemp = MessageDigest.getInstance(method);   
            mdTemp.update(strTemp);  
            byte[] md = mdTemp.digest();  
            int j = md.length;  
            char str[] = new char[j * 2];  
            int k = 0;  
            for (int i = 0; i < j; i++) {  
                byte byte0 = md[i];  
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
                str[k++] = hexDigits[byte0 & 0xf];  
            }  
            return new String(str);  
        } catch (Exception e) {  
            return null;  
        }  
    }
}
